const path = require('node:path')
const fs = require('node:fs')
const { Console } = require('node:console')
const { logLevel, configPath } = require('../base-config')
const { sleep } = require('./common')

const recordFile = path.join(configPath, 'record.log');

class Logger {
    constructor() {
        this.level = !logLevel ? 1 : ['debug', 'info', 'warn', 'error', 'off'].indexOf(logLevel)
        this.console = new Console({ stdout: process.stdout, stderr: process.stderr })
    }
    setLevel(levelName) {
        this.level = ['debug', 'info', 'warn', 'error', 'off'].indexOf(levelName)
    }
    debug(message, ...optionParams) {
        if (this.level <= 0) {
            this.console.debug(message, ...optionParams)
            this.recording && this.recorder.debug(message, ...optionParams)
        }
    }
    info(message, ...optionParams) {
        if (this.level <= 1) {
            this.console.info(message, ...optionParams)
            this.recording && this.recorder.info(message, ...optionParams)
        }
    }
    warn(message, ...optionParams) {
        if (this.level <= 2){
            this.console.warn(message, ...optionParams)
            this.recording && this.recorder.warn(message, ...optionParams)
        }
            
    }
    error(message, ...optionParams) {
        if (this.level <= 3) {
            this.console.error(message, ...optionParams)
            this.recording && this.recorder.error(message, ...optionParams)
        }
            
    }
    log(message, ...optionParams) {
        if (this.level < 4) {
            this.console.log(message, ...optionParams)
            this.recording && this.recorder.log(message, ...optionParams)
        }
            
    }
    async startRecord() {
        const output = fs.createWriteStream(recordFile);
        this.recorder = new Console({ stdout: output, stderr: output });
        this.recorder.clear()
        await sleep(500)
        this.recording = true
    }
    async shiftRecord() {
        this.recording = false
        let recordContent =  ''
        try {
            await sleep(500)
            recordContent = fs.readFileSync(recordFile, 'utf8')
        } catch (error) {}
        return recordContent
    }
}

module.exports = new Logger()